package com.example.senior_config.converter;

import com.example.senior_config.pojo.DemoObj;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @description 自定义的数据转换
 * @author ljw
 * @date 2021/9/9 7:10
 */
public class MyMessageConverter extends AbstractHttpMessageConverter<DemoObj> {

    public MyMessageConverter() {
        //新建一个自定义的媒体类型 application/x-wisely
        super(new MediaType("application", "x-wisely", Charset.forName("UTF-8")));
    }

    /**
     * 支持的类
     * @param
     * @author ljw
     * @date 2021/9/9 7:17
     */
    @Override
    protected boolean supports(Class<?> clazz) {
        return DemoObj.class.isAssignableFrom(clazz);
    }

    /**
     * 从前端接收到的数据转 DemoObj 对象
     * @param
     * @author ljw
     * @date 2021/9/9 7:22
     */
    @Override
    protected DemoObj readInternal(Class<? extends DemoObj> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
        String tmp = StreamUtils.copyToString(httpInputMessage.getBody(), Charset.forName("UTF-8"));
        String[] tmpArr = tmp.split("-");
        return new DemoObj(Long.valueOf(tmpArr[0]), tmpArr[1]);
    }

    /**
     * 将后台 DemoObj 转换为字符串数据输出到response
     * @param
     * @author ljw
     * @date 2021/9/9 7:27
     */
    @Override
    protected void writeInternal(DemoObj demoObj, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
        String out = demoObj.getId() + "-" + demoObj.getName();
        httpOutputMessage.getBody().write(out.getBytes(Charset.forName("UTF-8")));
    }
}
